/**
 * Created by huxia on 2016/12/9.
 */
var Hospital = require('./db')['hospital'];
var Area = require('./db')['crm_area'];

Hospital.findById = function (hp_id) {
    return Hospital.findOne({
        where: {
            id: hp_id
        }
    });
};
/*
    通过所在区域查找，无论医院级别是多少 */
Hospital.findByArea = function (a_id) {
    return Hospital.findAll({
        attribute:['name'],
        where: {
            area_id: a_id
        }
    });
};
/*
    通过所在城市查找，无论医院级别是多少 */
Hospital.findByCity = function (c_id) {
    var list_hp = [];
    return Area.findAll({
        where: {
            parent_id: c_id
        }
    }).then(function (list_area) {
        var areas = [];
        areas.push(c_id);
        list_area.forEach(function (item) {
            areas.push(item.dataValues.area_id);
        });
        return Hospital.findAll({
            where: {
                area_id: areas
            }
        });
    }).then(function (list_hp_f) {
        list_hp_f.forEach(function (item) {
            list_hp.push(item);
        });
        return list_hp;
    });
};
/*
    通过所在区域和医院级别查找，医院级别为0到9 */
Hospital.findByAreaAndLevel = function (a_id, h_level) {
    var hl = [];
    if (h_level > 0 && h_level < 4) {
        hl = [h_level];
    }
    else {
        hl = [1, 2, 3];
    }

    return Hospital.findAll({
        attribute: ['name'],
        where: {
            '$and': [
                {area_id: a_id},
                {level: hl}
            ]
        }
    });
};
/*
    通过所在城市和医院级别查找，医院级别为0到9 */
Hospital.findByCityAndLevel = function (c_id, h_level) {
    var hl = [];
    if (h_level > 0 && h_level < 4) {
        hl = [h_level];
    }
    else {
        hl = [1, 2, 3];
    }
    var list_hp = [];
    return Area.findAll({
        where: {
            parent_id: c_id
        }
    }).then(function (list_area) {
        var areas = [];
        areas.push(c_id);
        list_area.forEach(function (item) {
            areas.push(item.dataValues.area_id);
        });
        return Hospital.findAll({
            where: {
                '$and': [
                    {area_id: areas},
                    {level: hl}
                ]
            }
        });
    }).then(function (list_hp_f) {
        list_hp_f.forEach(function (item) {
            list_hp.push(item);
        });
        return list_hp;
    });
};

module.exports = Hospital;